trigger EventCallPlanSyncForSaloonAndPocketsession on HCPEducation__c (after insert,after update,before delete){
boolean b=false;
if(system.trigger.isupdate){
for(HCPEducation__c t:trigger.new){
    if(trigger.oldmap.get(t.id).date__c!=t.date__c){
        b=true;
    }
}
}
   List<Event> eventl=new List<Event>();
   list<id> idl=new list<id>();
   string name;
   datetime newdate;
   datetime olddate;
   list<datetime> cpdate=new list<datetime>();
   list<recordtype> allrtl=[select id,name,sobjecttype,developername from recordtype where (sobjecttype=:'event' and developername=:'PocketSessionOrSaloon') 
                                           or (sobjecttype=:'hcpeducation__c' and developername=:'PocketSession')
                                           or (sobjecttype=:'callplan__c' and developername=:'PS')
                                           or (sobjecttype=:'event' and developername=:'PClass')
                                           or (sobjecttype=:'event' and developername=:'CallPlan')
                                           or (sobjecttype=:'event' and developername=:'nationalHCP')
                                           ];
   recordtype rt;    //=[select id from recordtype where sobjecttype=:'event' and name=:'全国职业医护人员活动/科内会/学术沙龙'];
   list<event> eventupd=new list<event>();
   list<event> eventins=new list<event>();
   recordtype psrt;  //=[select id from recordtype where sobjecttype=:'hcpeducation__c' and name=:'科内会'];
   recordtype cppsrt;  //=[select id from recordtype where sobjecttype=:'callplan__c' and name=:'科内会'];

   recordtype epcrt;
   recordtype ecprt;
   recordtype enart;
   for(recordtype a:allrtl){
       if(a.sobjecttype=='event' && a.developername=='PocketSessionOrSaloon'){
           rt=a;
       }
       if(a.sobjecttype=='hcpeducation__c' && a.developername=='PocketSession'){
           psrt=a;
       }
       if(a.sobjecttype=='callplan__c' && a.developername=='PS'){
           cppsrt=a;
       }
       if(a.sobjecttype=='event' && a.developername=='PClass'){
           epcrt=a;
       }
       if(a.sobjecttype=='event' && a.developername=='CallPlan'){
           ecprt=a;
       }
       if(a.sobjecttype=='event' && a.developername=='nationalHCP'){
           enart=a;
       }
   }
   
   
   if(System.Trigger.Isinsert||System.Trigger.Isupdate){
   for(hcpeducation__c c:trigger.new){
    newdate = datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
    for(integer i=1;i<=30;i++){
        cpdate.add(newdate);
        newdate=newdate.addMinutes(30);
    }
   }
   if(system.trigger.isupdate){
   for(hcpeducation__c c:trigger.old){
    olddate = datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
    for(integer i=1;i<=30;i++){
        cpdate.add(olddate);
        olddate=olddate.addMinutes(30);
    }
   }
   }
 id rid;
for(hcpeducation__c c:trigger.new){
  if(system.trigger.isinsert){
  if(c.recordtypeid==psrt.id){
      rid=rt.id;
  }else{
      rid=enart.id;
  }
  
  if(c.time__c=='下午'){
                Event e = new Event(Subject=c.HCPeducationactivitytype__c, 
                                    WhatId=c.Id,
                                    recordtypeid=rid,
                                    StartDateTime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 6, 0, 0),
                                    EndDateTime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 9, 0, 0),
                                    IsReminderSet = false,
                                    hospitalname__c=c.Hospital__r.name,
                                    eventdate__c=c.date__c
                                    );
                  eventins.add(e);
      }else{
               Event e = new Event(Subject=c.HCPeducationactivitytype__c, 
                                    WhatId=c.Id,
                                    recordtypeid=rid,
                                    StartDateTime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 1, 0, 0),
                                    EndDateTime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 4, 0, 0),
                                    IsReminderSet = false,
                                    hospitalname__c=c.Hospital__r.name,
                                    eventdate__c=c.date__c
                                    );
                   eventins.add(e);
      }
                
       }
}
if(eventins.size()>0){
    insert eventins;
}

list<event> all=[select id,StartDateTime,whatid,recordtypeid from event e where e.ownerid=:userinfo.getuserid() and e.startdatetime in :cpdate order by  hospitalname__c];
if(system.trigger.isupdate){
for(hcpeducation__c c:trigger.new){
if(c.recordtypeid != psrt.id){
    for(event a:all){
        if(a.whatid==c.id){ 
         if(c.time__c=='上午'){
             a.startdatetime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 1, 0, 0);
         }else{
             a.startdatetime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 6, 0, 0);
         }
        }
    }
    }
}
update all;
}

if((system.trigger.isupdate&&b)||system.trigger.isinsert){

list<event> pocketl=new list<event>();
list<event> pclassl=new list<event>();
list<event> callplanl=new list<event>();
list<event> updatel=new list<event>();
datetime datime;

if(system.trigger.isupdate){
for(hcpeducation__c c:trigger.new){
if(c.recordtypeid == psrt.id){
    for(event a:all){
        if(a.whatid==c.id){ 
            a.startdatetime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
        }
    }
    }
}
update all;
}
for(hcpeducation__c c:trigger.new){
if(updatel.size()>0){
    if( updatel[0].startdatetime.date() != c.date__c){
        update updatel;
    }
    updatel.clear();
}
pocketl.clear();
pclassl.clear();
callplanl.clear();
    datime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
    for(event e:all){
      if(e.StartDateTime.date()==c.date__c){
        if(e.recordtypeid==rt.id){
            pocketl.add(e);
        }
        if(e.recordtypeid==epcrt.id){
            pclassl.add(e);
        }
        if(e.recordtypeid==ecprt.id){
            callplanl.add(e);
        }
      }
    }
    
    for(event p:pocketl){
        p.StartDateTime=datime;
        datime=datime.addHours(1);
        p.EndDateTime=datime;
        updatel.add(p);
    }
    for(event p:pclassl){
        p.StartDateTime=datime;
        datime=datime.addHours(1);
        p.EndDateTime=datime;
         updatel.add(p);
    }
    for(event p:callplanl){
        p.StartDateTime=datime;
        datime=datime.addMinutes(30);
        p.EndDateTime=datime;
         updatel.add(p);
    }
    
}
if(system.trigger.isupdate){
for(hcpeducation__c c:trigger.old){
pocketl.clear();
pclassl.clear();
callplanl.clear();
    datime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
    for(event e:all){
      if(e.StartDateTime.date()==c.date__c&&e.whatid!=c.id){
        if(e.recordtypeid==rt.id){
            pocketl.add(e);
        }
        if(e.recordtypeid==epcrt.id){
            pclassl.add(e);
        }
        if(e.recordtypeid==ecprt.id){
            callplanl.add(e);
        }
      }
    }
    
    for(event p:pocketl){
        p.StartDateTime=datime;
        datime=datime.addHours(1);
        p.EndDateTime=datime;
        updatel.add(p);
    }
    for(event p:pclassl){
        p.StartDateTime=datime;
        datime=datime.addHours(1);
        p.EndDateTime=datime;
         updatel.add(p);
    }
    for(event p:callplanl){
        p.StartDateTime=datime;
        datime=datime.addMinutes(30);
        p.EndDateTime=datime;
         updatel.add(p);
    }
    
}
}

update updatel;
}
   
   
   
   /*
       if(idl.size()>0){
           idl.clear();
       }
      for(HCPEducation__c he:trigger.new){
           idl.add(he.id);
      }  
      
      eventl=[select Subject,WhatId,StartDateTime,EndDateTime from Event where whatId in:idl];
      if(eventl.size()>0){                    //update code
                
                for(HCPEducation__c he:trigger.new){
                      time starttime = time.newInstance(9,0,0,0);
                      time endtime = time.newInstance(9,0,0,0);
                      if(he.time__c == '上午'){
                          starttime = time.newInstance(9,0,0,0);
                          endtime=time.newInstance(12,0,0,0);
                      }
                      else if (he.time__c == '下午'){
                          starttime = time.newInstance(14,0,0,0);
                          endtime = time.newInstance(17,0,0,0);
                      }
                     Datetime startdate=datetime.newinstance(he.date__c,starttime);
                     Datetime enddate=datetime.newinstance(he.date__c,endtime);
                     
                     for(event e:eventl){
                          if(e.whatid==he.id){
                                  e.StartDateTime=startdate;
                                  e.EndDateTime=enddate;
                                  e.IsReminderSet = false;
                                  eventupd.add(e);
                          }
                     }
                }
       }else if(eventl.size()==0){                //insert code
               for(HCPEducation__c he:trigger.new){
                      time starttime = time.newInstance(9,0,0,0);
                      time endtime = time.newInstance(9,0,0,0);
                      if(he.time__c == '上午'){
                          starttime = time.newInstance(9,0,0,0);
                          endtime=time.newInstance(12,0,0,0);
                      }
                      else if (he.time__c == '下午'){
                          starttime = time.newInstance(14,0,0,0);
                          endtime = time.newInstance(17,0,0,0);
                      }
                     Datetime startdate=datetime.newinstance(he.date__c,starttime);
                     Datetime enddate=datetime.newinstance(he.date__c,endtime);
                     
                     Event e=new Event(Subject=he.HCPeducationactivitytype__c,
                                WhatId=he.Id,
                                RecordTypeId=rt.id,
                                StartDateTime=startdate,
                                EndDateTime=enddate,
                                IsReminderSet = false
                                 );       
                     eventins.add(e);            
                                            
             }        
       }
      update eventupd;
      insert eventins;
      */
      
      
      //=====below is use for sync to callplan
            List<hcpeducation__c> psl=new list<hcpeducation__c>();
            list<callplan__c> cpins=new list<callplan__c>();
            list<callplan__c> cpupd=new list<callplan__c>();
            list<id> psmark=new list<id>();
            list<monthlycallplan__c> mcpins=new list<monthlycallplan__c>();
            list<hcpeducation__c> storeps=new list<hcpeducation__c>();
            list<datetime> sdt=new list<datetime>();
            
            list<MonthlyCallPlan__c> mcpl=new list<MonthlyCallPlan__c>();
            string month;
            string year;
            integer currentdate;
            time t;
            datetime dt;
            boolean mark=true;
            string dtime;

            mcpl=[select id,PlanYear__c,PlanMonth__c from monthlycallplan__c where ownerid=:userinfo.getuserid()];
            string plantype;
            
      if(system.trigger.isinsert && trigger.new[0].recordtypeid==psrt.id && trigger.new[0].date__c>date.today()){
           
            for(hcpeducation__c ps:trigger.new){
                month=ps.date__c.month()+'月';
                year=ps.date__c.year()+'';
                currentdate=((ps.date__c.year()*12)+ps.date__c.month())-((date.today().year()*12)+date.today().month());

                    plantype='计划内';


                if(ps.time__c == '上午'){
                        t= time.newInstance(9,0,0,0);
                }
                else if (ps.time__c == '下午'){
                        t = time.newInstance(14,0,0,0);
                }
                dt=datetime.newinstance(ps.date__c,t);

                for(monthlycallplan__c mcp:mcpl){
                    if(year==mcp.planyear__c && month==mcp.planmonth__c){
                        callplan__c cp=new callplan__c(name='科内会:'+ps.name,recordtypeid=cppsrt.id,
                        PlanType__c=plantype,CallPurpose__c='其他',CallPlanDate__c=ps.date__c,CallDate__c=dt,
                        //Lasts__c=1,
                        CallWorkingtype__c='科内会',Monthly_Call_Plan__c=mcp.id,CallMessage__c=ps.Messaging__c,activityid__c=ps.id);
                        cpins.add(cp);
                        mark=false;
                    }
                }
                if(mark){
                    monthlycallplan__c newmcp=new monthlycallplan__c(PlanMonth__c=month,planyear__c=year,name=userinfo.getlastname()+userinfo.getfirstname() + year + '年' + month + '拜访计划');
                    insert newmcp;
                    callplan__c cp=new callplan__c(name='科内会:'+ps.name,recordtypeid=cppsrt.id,
                        PlanType__c=plantype,CallPurpose__c='其他',CallPlanDate__c=ps.date__c,CallDate__c=dt,
                        //Lasts__c=1,                    
                        CallWorkingtype__c='科内会',Monthly_Call_Plan__c=newmcp.id,CallMessage__c=ps.Messaging__c,activityid__c=ps.id);
                        cpins.add(cp);
                }
              
            }
           
         
      }
      
      else if(system.trigger.isupdate && trigger.new[0].recordtypeid==psrt.id && trigger.old[0].date__c>date.today()){
             for(hcpeducation__c ps:trigger.old){
                month=ps.date__c.month()+'月';
                year=ps.date__c.year()+'';

                currentdate=((ps.date__c.year()*12)+ps.date__c.month())-((date.today().year()*12)+date.today().month());
                plantype='计划内';

                if(ps.time__c == '上午'){
                        t= time.newInstance(17,0,0,0);
                        dtime='AM(9am-12am)';
                }
                else if (ps.time__c == '下午'){
                        t = time.newInstance(22,0,0,0);
                        dtime='PM(2pm-5pm)';
                }
                dt=null;
                dt=datetime.newinstance(ps.date__c,t);
                name='科内会:'+trigger.old[0].name;
            }

            list<callplan__c> cpl=new list<callplan__c>();
            list<callplan__c> ucpl=new list<callplan__c>();
            ucpl=[select id from callplan__c where activityid__c=:trigger.old[0].id and IsDeleted =: false];//  LastModifiedDate=:trigger.old[0].LastModifiedDate and  CallPlanDate__c=:trigger.old[0].date__c and name=:name and ownerid__c=:string.valueof(trigger.old[0].ownerid).substring(0,15)

            for(hcpeducation__c ps:trigger.new){
                month=ps.date__c.month()+'月';
                year=ps.date__c.year()+'';
                currentdate=((ps.date__c.year()*12)+ps.date__c.month())-((date.today().year()*12)+date.today().month());
                

                plantype='计划内';
                    
                if(ps.time__c == '上午'){
                        t= time.newInstance(9,0,0,0);
                }
                else if (ps.time__c == '下午'){
                        t = time.newInstance(14,0,0,0);
                }
                dt=datetime.newinstance(ps.date__c,t);
/*by scao */
                for(callplan__c cp:ucpl){
                   cp.delete_mark__c=true;

                }



/*by siheng              
            for(callplan__c cpl1:ucpl){
                 delete cpl1;
            }
*/            

                for(monthlycallplan__c mcp:mcpl){
                    if(year==mcp.planyear__c && month==mcp.planmonth__c){
                        callplan__c cp=new callplan__c(name='科内会:'+ps.name,recordtypeid=cppsrt.id,
                        PlanType__c=plantype,CallPurpose__c='其他',CallPlanDate__c=ps.date__c,CallDate__c=dt,
                        //Lasts__c=1,
                     
                        CallWorkingtype__c='科内会',Monthly_Call_Plan__c=mcp.id,CallMessage__c=ps.Messaging__c,ActivityId__c=ps.id);
                        cpins.add(cp);
                        mark=false;
                    }
                }
                if(mark){
                    monthlycallplan__c newmcp=new monthlycallplan__c(PlanMonth__c=month,planyear__c=year,name=userinfo.getlastname()+userinfo.getfirstname() + year + '年' + month + '拜访计划');
                    insert newmcp;
                    callplan__c cp=new callplan__c(name='科内会:'+ps.name,recordtypeid=cppsrt.id,
                        PlanType__c=plantype,CallPurpose__c='其他',CallPlanDate__c=ps.date__c,CallDate__c=dt,
                        //Lasts__c=1,
                    
                        CallWorkingtype__c='科内会',Monthly_Call_Plan__c=newmcp.id,CallMessage__c=ps.Messaging__c,ActivityId__c=ps.id);
                        cpins.add(cp);
                }
          }
        update ucpl;
        delete ucpl;            
      }
    
        insert cpins;
     
    
      
      /*for(HCPEducation__c he:trigger.new){
      time starttime = time.newInstance(9,0,0,0);
      time endtime = time.newInstance(9,0,0,0);
      if(he.time__c == '上午'){
          starttime = time.newInstance(9,0,0,0);
          endtime=time.newInstance(12,0,0,0);
      }
      else if (he.time__c == '下午'){
          starttime = time.newInstance(14,0,0,0);
          endtime = time.newInstance(17,0,0,0);
      }
     Datetime startdate=datetime.newinstance(he.date__c,starttime);
     Datetime enddate=datetime.newinstance(he.date__c,endtime);
 
        if(System.Trigger.Isinsert){
 
              Event e=new Event(Subject=he.HCPeducationactivitytype__c,
                                WhatId=he.Id,
                                RecordTypeId=rt.id,
                                StartDateTime=startdate,
                                EndDateTime=enddate,
                                IsReminderSet = false, 
                                ReminderDateTime = startdate.addMinutes(-15)
                                 );   insert e; }                
                                 
                                 
        else if(System.trigger.isupdate){
              eventl=[select Subject,WhatId,StartDateTime,EndDateTime from Event where whatId=:he.id];
              if(eventl.size()>0){
              Event e=eventl[0];
              e.StartDateTime=startdate;
              e.EndDateTime=enddate;
              e.IsReminderSet=false;
              e.ReminderDateTime=startdate.addminutes(-15);
              
              update e;
             
              }
             }
           
            } */
            
        
   }else if(System.Trigger.Isdelete){
   
       if(idl.size()>0){
           idl.clear();
       }
        for(HCPEducation__c he:trigger.old){   
             idl.add(he.id);
         }
         eventl=[select Subject,WhatId,StartDateTime,EndDateTime from Event where whatId in:idl];
         if(eventl.size()>0){
             delete eventl;
         }
          
for(hcpeducation__c c:trigger.old){
    newdate = datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
    for(integer i=1;i<=30;i++){
        cpdate.add(newdate);
        newdate=newdate.addMinutes(30);
    }
}
    

//string soql='select id,StartDateTime,whatid from event e where e.ownerid=userinfo.getuserid() and e.startdatetime in cpdate order by (select name from callplan__c where id=e.whatid)';//查询出所有当日的event
//list<event> all=Database.query(soql);
list<event> all=[select id,StartDateTime,whatid,recordtypeid from event e where e.ownerid=:userinfo.getuserid() and e.startdatetime in :cpdate order by hospitalname__c];
list<event> pocketl=new list<event>();
list<event> pclassl=new list<event>();
list<event> callplanl=new list<event>();
list<event> updatel=new list<event>();
datetime datime;
for(hcpeducation__c c:trigger.old){
    if(updatel.size()>0){
    if( updatel[0].startdatetime.date() != c.date__c){
        update updatel;
    }
    updatel.clear();
    }
    pocketl.clear();
    pclassl.clear();
    callplanl.clear();
    datime=datetime.newInstancegmt(c.date__c.year(),c.date__c.month(),c.date__c.day(), 0, 0, 0);
    for(event e:all){
      if(e.StartDateTime.date()==c.date__c){
        if(e.recordtypeid==rt.id){
            pocketl.add(e);
        }
        if(e.recordtypeid==epcrt.id){
            pclassl.add(e);
        }
        if(e.recordtypeid==ecprt.id){
            callplanl.add(e);
        }
      }
    }
    
    for(event p:pocketl){
        p.StartDateTime=datime;
        datime=datime.addHours(1);
        p.EndDateTime=datime;
        updatel.add(p);
    }
    for(event p:pclassl){
        p.StartDateTime=datime;
        datime=datime.addHours(1);
        p.EndDateTime=datime;
         updatel.add(p);
    }
    for(event p:callplanl){
        p.StartDateTime=datime;
        datime=datime.addMinutes(30);
        p.EndDateTime=datime;
         updatel.add(p);
    }
    
}
update updatel;

    
    
      
                 string month;
                 string year;
                 integer currentdate;
                 string plantype;
                 time t;
                 string dtime;
                 datetime dt;
               
              for(hcpeducation__c ps:trigger.old){
                month=ps.date__c.month()+'月';
                year=ps.date__c.year()+'';
                currentdate=((ps.date__c.year()*12)+ps.date__c.month())-((date.today().year()*12)+date.today().month());
                
                if(currentdate>0){
                    plantype='计划内';
                }else{
                    plantype='计划外';
                }

                if(ps.time__c == '上午'){
                        t= time.newInstance(17,0,0,0);
                        dtime='AM(9am-12am)';
                }
                else if (ps.time__c == '下午'){
                        t = time.newInstance(22,0,0,0);
                        dtime='PM(2pm-5pm)';
                }
                dt=null;
                dt=datetime.newinstance(ps.date__c,t);
              name='科内会:'+trigger.old[0].name;
            }
            list<callplan__c> cpl=new list<callplan__c>();
            list<callplan__c> ucpl=new list<callplan__c>();
            ucpl=[select id from callplan__c where activityid__c=:trigger.old[0].id and IsDeleted =: false];//createddate=:trigger.old[0].createddate and name=:name and CallPlanDate__c=:trigger.old[0].date__c and ownerid__c=:userinfo.getuserid().substring(0,15)
         //   system.assert(false,ucpl.size());
           if(ucpl.size()>0){
                for(callplan__c cp:ucpl){
                   cp.delete_mark__c=true;
                }
                update ucpl;                
               delete ucpl;
           }
         
     }


  }